package com.superzqb.asus.superzqbFragment.superzqbMine;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.superzqb.asus.superzqb.R;
import com.superzqb.asus.superzqbFragment.superzqbMine.AreaInfoModel.BaseActivity;
import com.superzqb.asus.superzqbFragment.superzqbMine.AreaInfoModel.CityModel;
import com.superzqb.asus.superzqbFragment.superzqbMine.AreaInfoModel.DistrictModel;
import com.superzqb.asus.superzqbFragment.superzqbMine.AreaInfoModel.ProvinceModel;
import com.superzqb.asus.superzqbFragment.superzqbMine.AreaInfoModel.XmlParserHandler;
import com.superzqb.asus.superzqbUtil.LoadDialog;
import com.superzqb.asus.superzqbUtil.TreeLevelLinkage.OnWheelChangedListener;
import com.superzqb.asus.superzqbUtil.TreeLevelLinkage.WheelView;
import com.superzqb.asus.superzqbUtil.TreeLevelLinkage.adapters.ArrayWheelAdapter;
import com.superzqb.asus.superzqbUtil.Url;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * Created by asus on 2017/2/12.
 */

public class AreaInfo extends BaseActivity implements View.OnClickListener, OnWheelChangedListener {
    private final int SUCCESS = 0;
    private final int ERROR = 1;
    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;
    private Button mBtnConfirm;
    private Dialog loadingDialog;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case SUCCESS:
                    setUpData();
                    if(loadingDialog!=null)
                    loadingDialog.dismiss();
                    break;
                case ERROR:
                    if(loadingDialog!=null)
                    loadingDialog.dismiss();
                    Toast.makeText(AreaInfo.this, "获取失败", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mine_area_info);
        loadingDialog= LoadDialog.getInstance(this,"正在加载");
        loadingDialog.show();
        setUpViews();
        setUpListener();
        new Thread(networkTask).start();
    }
    Runnable networkTask = new Runnable() {

        @Override
        public void run() {
            // TODO
            // 在这里进行 http request.网络请求相关操作
            URL infoUrl;
            InputStream inStream = null;
            try {
                infoUrl = new URL(new Url().getAreaInfo());
                URLConnection connection = infoUrl.openConnection();
                HttpURLConnection httpConnection = (HttpURLConnection)connection;
                int responseCode = httpConnection.getResponseCode();
                if(responseCode == HttpURLConnection.HTTP_OK)
                {
                    inStream = httpConnection.getInputStream();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Message msg = new Message();
            if (inStream != null) {

                msg.obj = inStream;
                List<ProvinceModel> provinceList ;
                //AssetManager asset = getAssets();
                try {
                    InputStream input = inStream;
                    // 创建一个解析xml的工厂对象
                    SAXParserFactory spf = SAXParserFactory.newInstance();
                    // 解析xml
                    SAXParser parser = spf.newSAXParser();
                    XmlParserHandler handler = new XmlParserHandler();
                    parser.parse(input, handler);
                    input.close();
                    // 获取解析出来的数据
                    provinceList = handler.getDataList();
                    //*/ 初始化默认选中的省、市、区
                    if (provinceList != null && !provinceList.isEmpty()) {
                        mCurrentProviceName = provinceList.get(0).getName();
                        List<CityModel> cityList = provinceList.get(0).getCityList();
                        if (cityList != null && !cityList.isEmpty()) {
                            mCurrentCityName = cityList.get(0).getName();
                            List<DistrictModel> districtList = cityList.get(0).getDistrictList();
                            mCurrentDistrictName = districtList.get(0).getName();
                            mCurrentZipCode = districtList.get(0).getZipcode();
                        }
                    }
                    //*/
                    mProvinceDatas = new String[provinceList.size()];
                    for (int i = 0; i < provinceList.size(); i++) {
                        // 遍历所有省的数据
                        mProvinceDatas[i] = provinceList.get(i).getName();
                        List<CityModel> cityList = provinceList.get(i).getCityList();
                        String[] cityNames = new String[cityList.size()];
                        for (int j = 0; j < cityList.size(); j++) {
                            // 遍历省下面的所有市的数据
                            cityNames[j] = cityList.get(j).getName();
                            List<DistrictModel> districtList = cityList.get(j).getDistrictList();
                            String[] distrinctNameArray = new String[districtList.size()];
                            DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
                            for (int k = 0; k < districtList.size(); k++) {
                                // 遍历市下面所有区/县的数据
                                DistrictModel districtModel = new DistrictModel(districtList.get(k).getName(), districtList.get(k).getZipcode());
                                // 区/县对于的邮编，保存到mZipcodeDatasMap
                                mZipcodeDatasMap.put(districtList.get(k).getName(), districtList.get(k).getZipcode());
                                distrinctArray[k] = districtModel;
                                distrinctNameArray[k] = districtModel.getName();
                            }
                            // 市-区/县的数据，保存到mDistrictDatasMap
                            mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
                        }
                        // 省-市的数据，保存到mCitisDatasMap
                        mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
                    }
                    msg.what = SUCCESS;
                } catch (Throwable e) {
                    msg.what = ERROR;
                    e.printStackTrace();
                }
            } else {
                msg.what = ERROR;
            }
            handler.sendMessage(msg);
        }
    };

    private void setUpViews() {
        mViewProvince = (WheelView) findViewById(R.id.id_province);
        mViewCity = (WheelView) findViewById(R.id.id_city);
        mViewDistrict = (WheelView) findViewById(R.id.id_district);
        mBtnConfirm = (Button) findViewById(R.id.btn_confirm);
    }

    private void setUpListener() {
        // 添加change事件
        mViewProvince.addChangingListener(this);
        // 添加change事件
        mViewCity.addChangingListener(this);
        // 添加change事件
        mViewDistrict.addChangingListener(this);
        // 添加onclick事件
        mBtnConfirm.setOnClickListener(this);
    }
 /*   private void getAdressInfo1() {
        new Thread(){
            public void run() {
                URL infoUrl;
                InputStream inStream = null;
                try {
                    infoUrl = new URL(new Url().getAreaInfo());
                    URLConnection connection = infoUrl.openConnection();
                    HttpURLConnection httpConnection = (HttpURLConnection)connection;
                    int responseCode = httpConnection.getResponseCode();
                    if(responseCode == HttpURLConnection.HTTP_OK)
                    {
                        inStream = httpConnection.getInputStream();
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                InputStream newInfoList =inStream;
                Message msg = new Message();
                if (newInfoList != null) {
                    msg.what = SUCCESS;
                    msg.obj = newInfoList;
                } else {
                    msg.what = ERROR;
                }
                handler.sendMessage(msg);
            }
            private InputStream readEarthquakeDataFromInternet()
            {
                //从网络上获取实时地震数据
                URL infoUrl;
                InputStream inStream = null;
                try {
                    infoUrl = new URL(new Url().getAreaInfo());
                    URLConnection connection = infoUrl.openConnection();
                    HttpURLConnection httpConnection = (HttpURLConnection)connection;
                    int responseCode = httpConnection.getResponseCode();
                    if(responseCode == HttpURLConnection.HTTP_OK)
                    {
                        inStream = httpConnection.getInputStream();
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return inStream;
            }
        }.start();

    }*/

    private void setUpData() {
        //initProvinceDatas();

        mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(AreaInfo.this, mProvinceDatas));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        mViewDistrict.setVisibleItems(7);
        updateCities();
        updateAreas();
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        // TODO Auto-generated method stub
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        } else if (wheel == mViewDistrict) {
            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
            mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
        }
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
        String[] areas = mDistrictDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[] { "" };
        }
        mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
        mViewDistrict.setCurrentItem(0);
        mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[0];
        mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[] { "" };
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_confirm:
                showSelectedResult();
                break;
            default:
                break;
        }
    }

    private void showSelectedResult() {
        Toast.makeText(AreaInfo.this, "当前选中:"+mCurrentProviceName+","+mCurrentCityName+","
                +mCurrentDistrictName+","+mCurrentZipCode, Toast.LENGTH_SHORT).show();
    }
}

